/*
Just draw a border round the document.body.
*/
//DOM结构加载完毕
$(document).ready(function () {
    if (isBMC()) {
        $(window).resize(function () {
            console.log("窗口大小已变化。");
            setTimeout(function () {
                resizeKvm();
            }, 1)
        });
    }
});

// 页面渲染完成后的操作（如图片、样式表、脚本文件等）加载完成后
$(window).on("load", function () {
    if (isBMC()) {
        console.log('检测到KVM界面，修改div布局')
        domObserverBmc()
    }
});

function isBMC() {
    return window.location.pathname === "/viewer.html";
}

let debounceFuncBmc = throttle(function () {
    //一定要判断是否已处理，否则无限重复处理后和触发dom变更事件
    fixKvm()
}, 1);

function domObserverBmc() {
    // 创建一个MutationObserver对象
    var observer = new MutationObserver(function (mutations) {
        //一定要防抖或者判断是否已处理，否则不断重复处理后和触发dom变更事件
        debounceFuncBmc()
    });

// 配置MutationObserver要观察的目标
    var target = document.querySelector('body');
    var config = {childList: true, subtree: true};

// 开始观察DOM的变化
    observer.observe(target, config);
}


// 重新设置kvm显示高度
function resizeKvm() {
    let $bmcRight = $("#bmc_right");
    let $scrollDiv = $("#scroll_div");

    $scrollDiv.height(window.innerHeight - 4);

    var mgl = $bmcRight.css("marginLeft").replace("px", "");
    var pdl = $bmcRight.css("paddingLeft").replace("px", "");
    var borderPx = 4
    let bmc_width = $scrollDiv.width() + (parseInt(mgl) + parseInt(pdl) * 2) + borderPx;
    let number = $bmcRight.parent().width() - bmc_width
    $bmcRight.width(number);
}

function haveFix() {
    if ($("#button_help").length <= 0) {
        return false;
    }
    if ($("#scroll_div").width() + $("#bmc_right").width() >= window.innerWidth) {
        return true;
    }
    if ($(".chao-fix").length > 0) {
        return false;
    }
    return true
}

function fixKvm() {
    if (!haveFix()) {
        return;
    }

    // 局部细节调整
    $(".start_kvm").removeClass("col-md-4");
    $(".start_kvm").addClass("col-md-2");
    $(".div_dropdown").css({"float": "left"})

    //菜单栏
    $(".div_menu").addClass("bmc_menu chao-fix")
    // kvm显示居左
    $("#scroll_div").css({"float": "left"})

    let $bmcRight = $("#bmc_right");
    if ($bmcRight.length !== 1) {
        $bmcRight.remove()
        $("center").append("<div id='bmc_right'></div>")
    }

    //顶部部导航栏插入bmc控制div
    $bmcRight.append($(".bg_lavender .h5-toolbar"))
    $(".h5-toolbar").css({"padding-bottom": "0px"})

    //底部导航栏插入bmc控制div
    $bmcRight.append($("#lg-statusbar").parent())
    $("#lg-statusbar").css({"margin-top": "20px"})

    resizeKvm()

}